package cn.taofuxn.sale.util;

import org.assertj.core.util.Strings;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Properties;
import java.util.UUID;

/**
 * ProjectName : GeekSaleSystem
 * PackageName : cn.taofuxn.sale.util
 * Created by Wong
 * Date: 2018/3/15
 * Time: 17:28
 */
@Component
public class IdGenerater implements IdentifierGenerator,Configurable {
	private String prefix;
	
	
	
	
	@Override
	public void configure(final Type type, final Properties params, final ServiceRegistry serviceRegistry) throws MappingException {
		//这个会在实体上注解出来
		prefix = params.getProperty("base");
	}
	
	@Override
	public Serializable generate(final SessionImplementor session, final Object object) {
		Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);
		
		if(null != id)
			return id;
		
		String tGenId = UUID.randomUUID().toString().replace("-","");
		if(!Strings.isNullOrEmpty(prefix)){
			tGenId = prefix + tGenId;
		}
		
		return tGenId;
	}
}
